import 'dart:async';
import 'dart:convert' as convert;
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:full_display/common/qxp_color.dart';
import 'package:full_display/common/qxp_style.dart';
import 'package:full_display/generated/l10n.dart';
import 'package:full_display/page/single/single_provider.dart';
import 'package:full_display/provide/button_list_provider.dart';
import 'package:full_display/unit/asset_utils/asset_utils.dart';
import 'package:full_display/unit/screen/screen_utility.dart';
import 'package:full_display/unit/toast/progress_hud.dart';
import 'package:full_display/unit/toast/toast_util.dart';
import 'package:full_display/unit/web_socket/web_sockect_utils.dart';
import 'package:full_display/unit/widgets/drawer/drawer_widget.dart';
import 'package:full_display/unit/widgets/widget_button_list.dart';
import 'package:full_display/unit/widgets/widget_dialog/bluetooth_setting_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/clock_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/widget_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/wifi_setting_dialog.dart';
import 'package:full_display/unit/widgets/widget_media_list.dart';
import 'package:full_display/unit/widgets/widget_switch.dart';
import 'package:provider/provider.dart';

class SingleWenziWidget extends StatelessWidget {
  const SingleWenziWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => SingleProvider(),
        )
      ],
      child: const SingleAddWenziPage(),
    );
  }
}

class SingleAddWenziPage extends StatefulWidget {
  const SingleAddWenziPage({super.key});

  @override
  State<SingleAddWenziPage> createState() => _SingleAddWenziPageState();
}

class _SingleAddWenziPageState extends State<SingleAddWenziPage>
    with SingleTickerProviderStateMixin {
  TextEditingController infoController = TextEditingController();
  TextEditingController secController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  var _singleProvider = SingleProvider();

  String? colorStr;

  int? currentIndex;

  @override
  Widget build(BuildContext context) {
    _singleProvider = context.watch<SingleProvider>();
    return Scaffold(
      backgroundColor: ColorPlate.background,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: ColorPlate.background,
        elevation: 0,
        leading: IconButton(
          icon: Image.asset(
              height: 20.0.H, width: 20.0.W, AssetUtils.getAsset2Image("back")),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          // IconButton(
          //   icon: Image.asset(
          //     height: 24.0.H,
          //     width: 24.0.W,
          //     AssetUtils.getAsset2Image("icon_add"),
          //   ),
          //   onPressed: () {
          //     print("Search Pressed");
          //   },
          // ),
        ],
      ),
      body: GestureDetector(
        onTap: () {
          hideKeyboard(context);
        },
        child: Padding(
          padding: EdgeInsets.all(20.0.W),
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  S.of(context).entry_text,
                  textAlign: TextAlign.center,
                  style: StandardTextStyle.textWhite16Style,
                ),
                Container(
                  height: 10.0.H,
                ),
                inputTextWidget(infoController),
                Container(
                  height: 15.0.H,
                ),
                Text(
                  S.of(context).entry_duration,
                  textAlign: TextAlign.center,
                  style: StandardTextStyle.textWhite16Style,
                ),
                Container(
                  height: 10.0.H,
                ),
                inputSecWidget(secController),
                Container(
                  height: 15.0.H,
                ),
                Text(
                  S.of(context).entry_color,
                  textAlign: TextAlign.center,
                  style: StandardTextStyle.textWhite16Style,
                ),
                Container(
                  height: 10.0.H,
                ),
                Container(
                  height: 230.0,
                  child: GridView.builder(
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 10,
                            crossAxisSpacing: 6.0,
                            mainAxisSpacing: 6.0),
                    scrollDirection: Axis.vertical,
                    physics: NeverScrollableScrollPhysics(), // 设置禁止滚动
                    controller: _scrollController,
                    itemCount: SingleProvider.colorList.length,
                    itemBuilder: (context, index) {
                      return currentIndex == index
                          ? InkWell(
                              onTap: () {
                                hideKeyboard(context);
                                colorStr = SingleProvider.colorList[index];
                                setState(() {});
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Color(int.parse(
                                      '0xff${SingleProvider.colorList[index]}')),
                                  borderRadius: const BorderRadius.all(
                                      Radius.circular(4.0)),
                                  border:
                                      Border.all(width: 2, color: Colors.white),
                                ),
                                height: 28.0.W,
                                width: 28.0.W,
                              ),
                            )
                          : InkWell(
                              onTap: () {
                                hideKeyboard(context);
                                colorStr = SingleProvider.colorList[index];
                                setState(() {
                                  currentIndex = index;
                                });
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Color(int.parse(
                                      '0xff${SingleProvider.colorList[index]}')),
                                  borderRadius: const BorderRadius.all(
                                      Radius.circular(4.0)),
                                  border: Border.all(
                                      width: 2, color: Colors.transparent),
                                ),
                                height: 28.0.W,
                                width: 28.0.W,
                              ),
                            );
                    },
                  ),
                ),
                Container(
                  height: 50.0.H,
                ),
                Container(
                  width: double.infinity,
                  height: 44.0.H,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                        //渐变位置
                        begin: Alignment.topCenter, //右上
                        end: Alignment.bottomCenter, //左下
                        //渐变颜色[始点颜色, 结束颜色]
                        colors: [ColorPlate.app_blue, ColorPlate.sub_blue]),
                    borderRadius: BorderRadius.all(Radius.circular(22.0.H)),
                  ),
                  child: InkWell(
                    onTap: submitInfo,
                    child: Center(
                      child: Text(
                        S.of(context).entry_submit,
                        style: StandardTextStyle.textWhite16Style,
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget inputTextWidget(TextEditingController textVC) {
    return Container(
      height: 56.0.H,
      decoration: const BoxDecoration(
        color: ColorPlate.backgroundOpacity5,
        borderRadius: BorderRadius.all(Radius.circular(12.0)),
      ),
      child: Padding(
        padding: EdgeInsets.only(left: 20.0.W, right: 20.0.H, top: 5.0.W),
        child: TextField(
          cursorHeight: 20,
          style: const TextStyle(color: Colors.white),
          controller: textVC,
          decoration: InputDecoration(
            hintText: S.of(context).entry_text_tip,
            hintStyle: const TextStyle(color: ColorPlate.backgroundOpacity50),
            enabledBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: ColorPlate.backgroundOpacity0),
            ),
            focusedBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: ColorPlate.backgroundOpacity0),
            ),
          ),
          autofocus: true,
          cursorColor: ColorPlate.white,
        ),
      ),
    );
  }

  Widget inputSecWidget(TextEditingController textVC) {
    textVC.text = '15';
    return Container(
      height: 56.0.H,
      decoration: const BoxDecoration(
        color: ColorPlate.backgroundOpacity5,
        borderRadius: BorderRadius.all(Radius.circular(12.0)),
      ),
      child: Padding(
        padding: EdgeInsets.only(left: 20.0.W, right: 20.0.H, top: 5.0.W),
        child: TextField(
          cursorHeight: 20,
          style: const TextStyle(color: Colors.white),
          controller: textVC,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            hintText: S.of(context).entry_input_duration_tip,
            hintStyle: const TextStyle(color: ColorPlate.backgroundOpacity50),
            enabledBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: ColorPlate.backgroundOpacity0),
            ),
            focusedBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: ColorPlate.backgroundOpacity0),
            ),
          ),
          // autofocus: true,
          cursorColor: ColorPlate.white,
        ),
      ),
    );
  }

  void hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void submitInfo() {
    if (infoController.text.isEmpty) {
      showToast(S.of(context).input_text_noempty);
      return;
    }
    if (secController.text.isEmpty) {
      showToast(S.of(context).input_duration_noempty);
      return;
    }
    if (colorStr!.isEmpty) {
      showToast(S.of(context).select_color);
      return;
    }
    WebSocketUtils().sendCustomMessage(66, content: {
      'type': '3',
      "residencetime": int.parse(secController.text),
      "text": infoController.text,
      "color": "#$colorStr"
    });

    Future.delayed(Duration(seconds: 1), () {
      var param = {"text": infoController.text, "color": "#$colorStr"};
      print("param=======>${param}");
      List<int> list = convert.jsonEncode(param).codeUnits;
      Uint8List bytes = Uint8List.fromList(list);
      ByteData buff = ByteData.view(bytes.buffer);
      bufferData(buff, 0, 1);
    });
  }

  //发送单机数据包
  void bufferData(ByteData buff, index, pack_count) {
    print("index======${index}====cpunt====${pack_count}");
    int num = 15 + buff.lengthInBytes; //每个包的数据总长度
    Uint8List bufF = Uint8List(num);

    ByteData dataView = ByteData.view(bufF.buffer);

    var i = 0;

    dataView.setUint8(i, 0xfa);
    i++;
    dataView.setUint8(i, 0xf0);
    i++;
    dataView.setUint8(i, 66); //cmd
    i++;
    dataView.setUint8(i, 0); //number
    i++;
    dataView.setUint32(i, pack_count, Endian.little); //count
    i += 4;
    dataView.setUint32(i, index, Endian.little); //index
    i += 4;
    if (index == pack_count - 1) {
      dataView.setUint16(i, buff.lengthInBytes, Endian.little);
    } else {
      dataView.setUint16(i, (32 * 1024), Endian.little);
    }
    i += 2;
    ByteData dataView_data = ByteData.view(buff.buffer);
    //console.log('byteLength=', buff.byteLength);
    int k = 0;
    for (var j = 0; j < buff.lengthInBytes; j++) {
      k = j + 1;
      dataView.setUint8(i + j, dataView_data.getUint8(j));
    }
    i += k;
    dataView.setUint8(i, 254);
    WebSocketUtils()
        .sendCustomMessage(66, content: {"type": "2", "data": bufF});
    Navigator.pop(context);
  }
}
